﻿using B.S.BasicData.Api.Read.Applications.Commands.Accounts;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastcuture.Commons;
using B.S.BasicData.Infrastcuture.Interfaces;
using MediatR;
using System.Security.AccessControl;

namespace B.S.BasicData.Api.Read.Applications.CommandHandlers.Accounts
{
    public class DeptQueryCommandHandler : IRequestHandler<DeptQueryCommand, ApiResult<List<DeptmentDto>>>
    {
        private readonly IBaseRepository<Dept> baseRepository;

        public DeptQueryCommandHandler(IBaseRepository<Dept> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        public async Task<ApiResult<List<DeptmentDto>>> Handle(DeptQueryCommand request, CancellationToken cancellationToken)
        {
            var list = await Tree(0);
            return new ApiResult<List<DeptmentDto>>()
            {
                Code = ResultCode.SearchSuccess,
                Data=list,
                Message="",
            };
        }


        public async Task<List<DeptmentDto>> Tree(int ParentId)
        {
            var list=baseRepository.GetAll().Where(x=>x.ParentId==ParentId).ToList();
            List<DeptmentDto> trees=new List<DeptmentDto>();
            foreach (var item in list)
            {
                trees.Add(new DeptmentDto()
                {
                    value = item.DpetId,
                    label = item.DpetName,
                    children =await Tree(item.DpetId)

                });
            }
            return trees;

        }
    }
}
